package com.weiyuwqj.web;

import com.weiyuwqj.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class SessionFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    HttpSession session = request.getSession();
    Object userIdObj=session.getAttribute("userId");
    String path=request.getServletPath();

    String[] noNeedLoginPaths={"/user/login","/user/lottery/isLogin"};
    String[] needLoginPaths={"/user","/account","/invest"/*,"/item/doInvest"*/};

    boolean noNeedLogin=isMatch(path,noNeedLoginPaths);
    if(noNeedLogin){
      chain.doFilter(req,res);
    }else{
      boolean needLogin=isMatch(path,needLoginPaths);
      if(needLogin&&userIdObj==null){
        String queryString=request.getQueryString();
        if(StringUtils.isNull(queryString)){
          session.setAttribute("callback",path);
        }else{
          session.setAttribute("callback",path+"?"+queryString);
        }
        request.getRequestDispatcher("/login").forward(request, response);
      }else{
        chain.doFilter(req,res);
      }
    }

  }
  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

  private boolean isMatch(String path, String[] paths){
    boolean isMatch = false;
    for(String p:paths){
      if(path.startsWith(p)){
        isMatch = true;
        break;
      }
    }
    return isMatch;
  }

}
